package com.liuqi.loggers.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 初始化日志配置
 *
 * @author liuqi
 * @date 2024/11/5 14:40
 **/
public class Configuration {

    /**
     * 扩展日志级别后缀拼接
     */
    private final String expandLevelNameSuffix = Constants.DOT + Constants.ASTERISK;

    /**
     * 日志输出级别
     */
    private Level level = Level.TRACE;

    /**
     * 日志追加器
     */
    private List<Appender> appenderList = new ArrayList<Appender>();

    /**
     * 自定义日志级别
     *
     * 优先级高于 {@link #level}
     */
    private Map<String, Level> expandLevels = new HashMap<String, Level>();

    public void addAppender(Appender appender) {
        appenderList.add(appender);
    }

    public void addLevel(String name, Level level) {
        if (name == null) throw new NullPointerException("name not be null ");
        if (level == null) throw new NullPointerException("level not be null ");

        expandLevels.put(name + expandLevelNameSuffix, level);
    }

    public Level getLevel() {
        return level;
    }

    public void setLevel(Level level) {
        this.level = level;
    }

    public List<Appender> getAppenderList() {
        return appenderList;
    }

    public Map<String, Level> getExpandLevels() {
        return expandLevels;
    }

    /**
     * 通过日志实例名称获取日志级别
     *
     * @param name
     * @return
     */
    public Level getLevel(String name) {
        if (expandLevels.isEmpty()) {
            return level;
        }

        Set<String> expandLevelNames = expandLevels.keySet();
        for (String key : expandLevelNames) {
            if (name.matches(key)) {
                return expandLevels.get(key);
            }
        }

        return level;
    }

}
